package apptoko.com.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

import main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu.OnItemSelectedListener;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.RelativeLayout;
import android.widget.Toast;
import apptoko.com.CollectionUnitActivity;
import apptoko.com.ConfirmBuyActivity;
import apptoko.com.HomeStoreActivity;
import apptoko.com.ItemBrokerActivity;
import apptoko.com.LoginActivity;
import apptoko.com.SettingsActivity;
import apptoko.com.UILApplication;
import apptoko.com.adapter.ErrorHandler;
import apptoko.com.background.BackgroundTasks;
import apptoko.com.db.DatabaseHelper;
import apptoko.com.download.DownloadManager;
import apptoko.com.download.DownloadService;
import apptoko.com.download.DownloadManager.Request;
import apptoko.com.event.Event;
import apptoko.com.event.Event.BuyFailEvent;
import apptoko.com.event.Event.BuySuccessEvent;
import apptoko.com.event.Event.CollectionGroupEvent;
import apptoko.com.event.Event.EmptyEvent;
import apptoko.com.event.Event.GetDownloadLinkFailEvent;
import apptoko.com.event.Event.GetDownloadLinkSuccess;
import apptoko.com.event.Event.HomeScreenFailEvent;
import apptoko.com.event.Event.Level2CollectionListEvent;
import apptoko.com.event.Event.RequestFailEvent;
import apptoko.com.event.Event.UserInfoSuccessEvent;
import apptoko.com.model.CollectionList;
import apptoko.com.model.ContentItemInfo;
import apptoko.com.model.DownloadLaterItem;
import apptoko.com.model.DownloadLink;
import apptoko.com.model.GiftSetting;
import apptoko.com.network.InstallBackgroundTask;
import apptoko.com.network.ProgressDialogManager;
import apptoko.com.util.Constants;
import apptoko.com.util.StorageUtils;
import apptoko.com.util.Utils;
import apptoko.com.view.AlertDialogManager;
import apptoko.com.view.CustomHorizontalScrollView;
import apptoko.com.view.ScaleImageView;

import com.androidquery.AQuery;
import com.appota.asdk.topup.TopupAPI;
import apptoko.com.R;
import com.devspark.appmsg.AppMsg;
import com.google.analytics.tracking.android.EasyTracker;

import de.greenrobot.event.EventBus;

@SuppressLint("NewApi")
public class HomeContentFragment extends BaseFragment implements OnClickListener {

	private AQuery aq;
	private BackgroundTasks bgTask;
	private String accessToken;
	private EventBus eventBus;
	private View layoutCollectionItem;
	private View layoutCollectionList;
	private LayoutInflater inflater;
	private AQuery aqCL;
	private AQuery aqCI;
	private CustomHorizontalScrollView listItem;
	private LinearLayout parent;
	private Resources res;
	private Typeface robotoCond;
	private Typeface robotoItalic;
	private DatabaseHelper db;
	private ProgressDialog pDialog;
	private int greenTym = -1;
	private int purpleTym = -1;
	private ContentItemInfo contentItem;
	private DownloadManager downloadManager;
	private DialogInterface.OnClickListener onClick;
	private String countryCode;
	private String versionName = "";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		this.inflater = inflater;
		mParent = inflater.inflate(R.layout.activity_home, null);
		aq = new AQuery(mParent);
		Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), getResources().getString(R.string.roboto_light));
		aq.id(R.id.tv_apps).typeface(tf);
		aq.id(R.id.tv_games).typeface(tf);
		aq.id(R.id.tv_books).typeface(tf);
		aq.id(R.id.tv_comics).typeface(tf);
		aq.id(R.id.tv_film).typeface(tf);
		aq.id(R.id.tv_free_tym).typeface(tf);
		
		aq.id(R.id.btn_apps).clicked(this);
		aq.id(R.id.btn_games).clicked(this);
		if(!countryCode.equalsIgnoreCase("vn")){
			aq.id(R.id.btn_book).gone();
			aq.id(R.id.btn_comic).gone();
			aq.id(R.id.btn_film).gone();
			aq.id(R.id.btn_gift4u).gone();
		} else {
			aq.id(R.id.btn_book).visible();
			aq.id(R.id.btn_comic).visible();
			aq.id(R.id.btn_film).visible();
			aq.id(R.id.btn_gift4u).visible();
			aq.id(R.id.btn_book).clicked(this);
			aq.id(R.id.btn_comic).clicked(this);
			aq.id(R.id.btn_film).clicked(this);
			aq.id(R.id.btn_gift4u).clicked(this);
		}
		return mParent;
	}

	@Override
	protected void initVariables() {
		// TODO Auto-generated method stub
//		Exchanger.start(getActivity(), getString(R.string.metaps_exchanger_code), Exchanger.ORIENTATION_PORTRAIT, false);
		countryCode = Utils.getStaticCountryCode(mContext);
		EasyTracker.getInstance().setContext(mContext);
		db = new DatabaseHelper(mContext);
		eventBus = EventBus.getDefault();
		eventBus.register(this);
		bgTask = new BackgroundTasks(mContext);
		accessToken = Utils.getStaticAccessToken(getActivity());
		res = getResources();
		robotoCond = Typeface.createFromAsset(getActivity().getAssets(), res.getString(R.string.roboto_condensed));
		robotoItalic = Typeface.createFromAsset(getActivity().getAssets(), res.getString(R.string.roboto_italic_condensed));
		getUserInfo();
		downloadManager = new DownloadManager(mContext.getContentResolver(), mContext.getPackageName());
	    downloadManager.setAccessAllDownloads(false);
		startDownloadService();
	}
	
	private void startDownloadService() {
		Intent intent = new Intent();
		intent.setClass(getActivity(), DownloadService.class);
		getActivity().startService(intent);
	}

	private void getUserInfo(){
		String accessToken = Utils.getStaticAccessToken(getActivity());
		if(accessToken!="3de71f9e84a325bbfb86466c15b40b1e"){
			bgTask.getUserInfo(accessToken);
		}
	}
	
	public void onEventMainThread(UserInfoSuccessEvent event){
		greenTym = event.getUser().getGreenTym();
		purpleTym = event.getUser().getPurpleTym();
		getActivity().getSharedPreferences(Constants.SHARED_NAME, Activity.MODE_PRIVATE).edit().putString(Constants.USERNAME_LOGGEDIN, event.getUser().getUserName()).commit();
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		eventBus.unregister(this);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
	}

	@Override
	protected void initActions() {
		// TODO Auto-generated method stub
		accessToken = Utils.getStaticAccessToken(getActivity());
//		bgTask.getCollectionGroup(accessToken, Constants.ANDROID_STORE);
	}
	
	public void onEventMainThread(CollectionGroupEvent event){
		int groupId = event.getCollGroupList().get(0).getCollectionId();
		accessToken = Utils.getStaticAccessToken(getActivity());
//		bgTask.getLevel2CollectionList(accessToken, Constants.ANDROID_STORE, groupId);
	}
	
	public void onEventMainThread(final Level2CollectionListEvent event){
		List<CollectionList> level2CollectionList = event.getCollectionList();
		Collections.sort(level2CollectionList, new CustomComparator());
		View layout;
		ScaleImageView banner;
		AQuery aqBanner;
		int count = 0;
		for(final CollectionList cl : level2CollectionList){
			count++;
			if(count > 6){
				break;
			}
			if(cl.getOrder() % 3 == 0 && cl.getOrder() != 0){
				layout = inflater.inflate(R.layout.collection_banner, null);
				banner = (ScaleImageView) layout.findViewById(R.id.collection_banner);
				aqBanner = new AQuery(layout);
				aqBanner.id(banner).image(cl.getCover(), true, true);
				banner.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if(countryCode.equalsIgnoreCase("vn")){
							Intent intent = new Intent(getActivity(), CollectionUnitActivity.class);
							intent.putExtra(Constants.COLLECTION_LIST_ID, cl.getId());
							intent.putExtra(Constants.COLLECTION_TITLE, cl.getName());
							intent.putExtra(Constants.COLLECTION_COVER, cl.getCover());
							startActivity(intent);
						}
					}
				});
			} else {
				layoutCollectionList = inflater.inflate(R.layout.collection_list_item, null);
				layoutCollectionList.findViewById(R.id.collection_name).setSelected(true);
				aqCL = new AQuery(layoutCollectionList);
				aqCL.id(R.id.collection_name).text(cl.getName()).typeface(robotoItalic);
				aqCL.id(R.id.btn_coll_seemore).typeface(robotoCond).clicked(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if(countryCode.equalsIgnoreCase("vn")){
							Intent intent = new Intent(getActivity(), CollectionUnitActivity.class);
							intent.putExtra(Constants.COLLECTION_LIST_ID, cl.getId());
							intent.putExtra(Constants.COLLECTION_TITLE, cl.getName());
							intent.putExtra(Constants.COLLECTION_COVER, cl.getCover());
							startActivity(intent);
						} else {
							Intent i = new Intent(Intent.ACTION_VIEW);
							i.setData(Uri.parse("https://play.google.com/store/apps/collection/editors_choice"));
							startActivity(i);
						}
					}
				});
				listItem = (CustomHorizontalScrollView) layoutCollectionList.findViewById(R.id.horiz_list_item);
				parent = new LinearLayout(getActivity());
				parent.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
				layoutCollectionItem = inflater.inflate(R.layout.metaps_exchanger_item, null);
				AQuery aqm = new AQuery(layoutCollectionItem);
				RelativeLayout rl = (RelativeLayout) layoutCollectionItem.findViewById(R.id.coll_icon);
				aqm.id(R.id.coll_name).text(getString(R.string.metaps_name));
				aqm.id(R.id.coll_price).text(res.getString(R.string.free).toUpperCase(Locale.US)).typeface(robotoCond);
				aqm.id(R.id.coll_rating).rating(5);
//				ExchangerPreludeConfig config = new ExchangerPreludeConfig();
//				config.setIconSize(100);
//				ExchangerPrelude prelude = new ExchangerPrelude(getActivity(), null, config);
//				rl.addView(prelude);
				if(count == 1 && !Utils.getStaticIsRooted(getActivity())){
					parent.addView(layoutCollectionItem);
				}
				
				ContentItemInfo item;
				OnCollectionItemMenuClick onClick;
				int max = 0;
				if(cl.getContentList().size() > 7){
					max = 7;
				} else {
					max = cl.getContentList().size();
				}
				for(int i = 0; i < max; i++){
					item = cl.getContentList().get(i);
					layoutCollectionItem = inflater.inflate(R.layout.collection_item, null);
					aqCI = new AQuery(layoutCollectionItem);
					if(UILApplication.getInstance().isLoadAllImgs()){
						aqCI.id(R.id.coll_icon).visible();
						if(aqCI.getCachedFile(item.getAvatar())!=null){
							aqCI.id(R.id.coll_icon).image(aqCI.getCachedFile(item.getAvatar()),75);
							Log.e("NMN","getHomeContent images from Cachedfile");
						}else{
							Log.e("NMN","getHomeContent images from server");
							aqCI.id(R.id.coll_icon).image(item.getAvatar(), true, true, 0, 0, null, AQuery.FADE_IN_NETWORK, 1.0f/1.0f);
						}
					}else{
						aqCI.id(R.id.coll_icon).visibility(View.GONE);
					}
					
					aqCI.id(R.id.coll_name).text(item.getTitle()).typeface(robotoCond);
					int price = item.getPrice();
					if(price == 0){
						aqCI.id(R.id.coll_price).text(res.getString(R.string.free).toUpperCase(Locale.US)).typeface(robotoCond);
					} else {
						aqCI.id(R.id.coll_price).text(String.valueOf(price)).typeface(robotoCond);
					}
					aqCI.id(R.id.coll_rating).rating(item.getRating());
					final String slug = item.getApplicationId();
					if(item.getGiftbox() == 1){
						aqCI.id(R.id.ribbon_gift).visible();
					} else {
						aqCI.id(R.id.ribbon_gift).gone();
					}
					aqCI.id(R.id.item_container).clicked(new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							if(countryCode.equalsIgnoreCase("vn")){
								Intent intent = new Intent(getActivity(), ItemBrokerActivity.class);
								intent.putExtra(Constants.PREVIOUS_SCREEN, "home/collection/" + cl.getName());
								intent.putExtra(Constants.SLUG, slug);
								intent.putExtra(Constants.FROM, 3);
								intent.putExtra(Constants.KEY_REFERER, "direct");
								intent.putExtra(Constants.STORE_KEY, "apps");
								startActivity(intent);
							}
						}
					});
					onClick = new OnCollectionItemMenuClick(item);
					if(countryCode.equalsIgnoreCase("vn")){
						aqCI.id(R.id.btn_quick_menu).clicked(onClick);
					}
					parent.addView(layoutCollectionItem);
				}
				listItem.addView(parent);
			}
		}
	}
	
	private class OnCollectionItemMenuClick implements OnClickListener {
		private ContentItemInfo item;
		public OnCollectionItemMenuClick(ContentItemInfo item){
			this.item = item;
		}
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if(db.checkAppInstalled(item.getPackageName())){
				showInstalledMenu(v, item.getPackageName());
			} else {
				showNotInstalledMenu(v, item);
			}
		}
		
	}
	
	public void onEventMainThread(HomeScreenFailEvent event){
		ErrorHandler.getInstance().setContext(getActivity()).handleError(event.getErrorCode());
	}
	
	public void onEventMainThread(EmptyEvent event){
		//Toast.makeText(mContext, "empty", Toast.LENGTH_SHORT).show();
	}
	
	public void onEventMainThread(RequestFailEvent e){
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent;
		switch (v.getId()) {
			case R.id.btn_apps:
				EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.EVENT_ACTION, "ClickStoreAppsFromHome", Long.valueOf(1));
				intent = new Intent(getActivity(), HomeStoreActivity.class);
				intent.putExtra(Constants.STORE_KEY, "apps");
				intent.putExtra(Constants.NAV_POSITION, 0);
				startActivity(intent);
				break;
			case R.id.btn_games:
				EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.EVENT_ACTION, "ClickStoreGamesFromHome", Long.valueOf(1));
				intent = new Intent(getActivity(), HomeStoreActivity.class);
				intent.putExtra(Constants.STORE_KEY, "games");
				intent.putExtra(Constants.NAV_POSITION, 1);
				startActivity(intent);
				break;
			case R.id.btn_book:
				EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.EVENT_ACTION, "ClickStoreBooksFromHome", Long.valueOf(1));
				intent = new Intent(getActivity(), HomeStoreActivity.class);
				intent.putExtra(Constants.STORE_KEY, "books");
				intent.putExtra(Constants.NAV_POSITION, 2);
				startActivity(intent);
				break;
			case R.id.btn_comic:
				EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.EVENT_ACTION, "ClickStoreComicsFromHome", Long.valueOf(1));
				intent = new Intent(getActivity(), HomeStoreActivity.class);
				intent.putExtra(Constants.STORE_KEY, "comics");
				intent.putExtra(Constants.NAV_POSITION, 3);
				startActivity(intent);
				break;
			case R.id.btn_film:
				EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.EVENT_ACTION, "ClickStoreMoviesFromHome", Long.valueOf(1));
				intent = new Intent(getActivity(), HomeStoreActivity.class);
				intent.putExtra(Constants.STORE_KEY, "movies");
				intent.putExtra(Constants.NAV_POSITION, 4);
				startActivity(intent);
				break;
			case R.id.btn_gift4u:
//				EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.EVENT_ACTION, "ClickGiftFromHome", Long.valueOf(1));
//				intent = new Intent(getActivity(), GiftsActivity.class);
//				startActivity(intent);
				break;
		}
	}
	
	private class CustomComparator implements Comparator<CollectionList> {

		@Override
		public int compare(CollectionList obj1, CollectionList obj2) {
			// TODO Auto-generated method stub
			return obj1.getOrder() < obj2.getOrder() ? -1
			         : obj1.getOrder() > obj2.getOrder() ? 1
			         : 0;
		}
	}

	private void showInstalledMenu(View v, final String packageName){
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
			PopupMenu menu = new PopupMenu(mContext, v);
			menu.getMenuInflater().inflate(R.menu.installed_app_menu, menu.getMenu());
			menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
				@Override
				public boolean onMenuItemClick(MenuItem menuItem) {
					// TODO Auto-generated method stub
					switch (menuItem.getItemId()) {
					case R.id.menu_launch:
						Intent launch = mContext.getPackageManager().getLaunchIntentForPackage(packageName);
						launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						mContext.startActivity(launch);
						break;
					case R.id.menu_uninstall:
						Utils.uninstallAPK(mContext, packageName);
						break;
					}
					return true;
				}
			});
			menu.show();
		} else {
			main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu popupMenuCompat = new main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu(mContext);
			popupMenuCompat.add(1, R.string.menu_launch);
			popupMenuCompat.add(2, R.string.menu_uninstall);
			popupMenuCompat.setOnItemSelectedListener(new OnItemSelectedListener() {
				@Override
				public void onItemSelected(main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem menuItem) {
					switch (menuItem.getItemId()) {
					case 1:
						Intent launch = mContext.getPackageManager().getLaunchIntentForPackage(packageName);
						launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						mContext.startActivity(launch);
						break;
					case 2:
						Utils.uninstallAPK(mContext, packageName);
						break;
					}
				}
			});
			popupMenuCompat.show(v);
		}
	}
	
	private boolean checkLogin(){
		return Utils.getStaticIsLogin(getActivity());
	}
	
	private void checkGift(){
		if(contentItem.getGiftbox() == 1){
			AlertDialogManager am = new AlertDialogManager(mContext);
			final DatabaseHelper db = new DatabaseHelper(mContext);
			GiftSetting gift = db.getGiftSync(contentItem.getApplicationId());
			if(gift != null && gift.getReceived() == 1){
//				am.showPositiveDialog(R.string.gift_already_received, android.R.string.ok, new DialogInterface.OnClickListener() {
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						dialog.dismiss();
//					}
//				});
				download(contentItem);
			} else {
				if(contentItem.getGiftboxDaysToGet() == 0){
					final GiftSetting gs = new GiftSetting();
					gs.setReceived(0);
					gs.setDays(0);
					gs.setName(contentItem.getPackageName());
					gs.setSlug(contentItem.getApplicationId());
					gs.setAppName(contentItem.getTitle());
					gs.setPicture(contentItem.getAvatar());
					onClick = new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							db.addGift(gs);
							download(contentItem);
						}
					};
					am.showGiftDialog(R.string.gift_message, 0, onClick);
				} else {
					final GiftSetting gs = new GiftSetting();
					gs.setReceived(0);
					gs.setDays(contentItem.getGiftboxDaysToGet());
					gs.setName(contentItem.getPackageName());
					gs.setSlug(contentItem.getApplicationId());
					gs.setAppName(contentItem.getTitle());
					gs.setPicture(contentItem.getAvatar());
					gs.setTimeToReceive(Utils.calculateDaysToGetGift(contentItem.getGiftboxDaysToGet()));
					onClick = new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							db.addGift(gs);
							download(contentItem);
						}
					};
					am.showGiftDialog(R.string.gift_message_days, contentItem.getGiftboxDaysToGet(), onClick);
				}
			}
		} else {
			download(contentItem);
		}
	}
	
	private void download(ContentItemInfo item){
		pDialog = ProgressDialogManager.showProgressDialog(mContext, R.string.loading);
		if(item.getPrice() != 0){
			validAndBuy(item.getPrice(), "green", item, 0);
		} else if(item.getPrice2() != 0){
			validAndBuy(item.getPrice2(), "purple", item, 0);
		} else {
			validAndBuy(0, "free", item, 0);
		}
	}
	
	private void showNotInstalledMenu(View v, final ContentItemInfo item){
		this.contentItem = item;
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
			PopupMenu menu = new PopupMenu(mContext, v);
			menu.getMenuInflater().inflate(R.menu.not_installed_app_menu,menu.getMenu());
			menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
				@Override
				public boolean onMenuItemClick(MenuItem menuItem) {
					// TODO Auto-generated method stub
					switch (menuItem.getItemId()) {
					case R.id.menu_install:
						EasyTracker.getTracker().sendEvent(Constants.DOWNLOAD_EVENT_CATEGORY, Constants.COLLECTION_DOWNLOAD_ACTION, item.getTitle() + " in android store", Long.valueOf(1));
						if(!countryCode.equalsIgnoreCase("vn")){
							if(item.getRootLink()!=null)
							{
								Intent gp = new Intent(Intent.ACTION_VIEW);
								gp.setData(Uri.parse(item.getRootLink()));
								startActivity(gp);
							}
							
						} else {
							if(checkLogin()){
								checkGift();
							} else {
								AlertDialogManager am = new AlertDialogManager(mContext);
								am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										// TODO Auto-generated method stub
										switch (which) {
										case DialogInterface.BUTTON_POSITIVE:
											Intent intent = new Intent(getActivity(), LoginActivity.class);
											intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
											startActivity(intent);
											break;
										case DialogInterface.BUTTON_NEGATIVE:
											dialog.dismiss();
											break;
										}
									}
								});
							}
						}
						break;
					case R.id.menu_add_wishlist:
						DatabaseHelper db = new DatabaseHelper(mContext);
						DownloadLaterItem dlItem = new DownloadLaterItem(item.getAvatar(), item.getTitle(), item.getAuthor(), item.getApplicationId());
						dlItem.setPrice1(item.getPrice());
						dlItem.setPrice2(item.getPrice2());
						dlItem.setPackageName(item.getPackageName());
						dlItem.setType(Constants.ANDROID_STORE);
						boolean added = db.addDownloadLater(dlItem);
						if(added){
							Toast.makeText(mContext, String.format(getResources().getString(R.string.saved), item.getTitle()), Toast.LENGTH_SHORT).show();
						} else {
							Toast.makeText(mContext, String.format(getResources().getString(R.string.item_exist), item.getTitle()), Toast.LENGTH_SHORT).show();
						}
						break;
					}
					return true;
				}
			});
			menu.show();
		} else {
			main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu popupMenuCompat = new main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu(mContext);
			popupMenuCompat.add(1, R.string.install);
			popupMenuCompat.add(2, R.string.add_to_wishlist);
			popupMenuCompat.setOnItemSelectedListener(new OnItemSelectedListener() {
				@Override
				public void onItemSelected(main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem menuItem) {
					switch (menuItem.getItemId()) {
					case 1:
						EasyTracker.getTracker().sendEvent(Constants.DOWNLOAD_EVENT_CATEGORY, Constants.COLLECTION_DOWNLOAD_ACTION, item.getTitle() + " in android store", Long.valueOf(1));
						if(checkLogin()){
							checkGift();
						} else {
							AlertDialogManager am = new AlertDialogManager(mContext);
							am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									switch (which) {
									case DialogInterface.BUTTON_POSITIVE:
										Intent intent = new Intent(getActivity(), LoginActivity.class);
										intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
										startActivity(intent);
										break;
									case DialogInterface.BUTTON_NEGATIVE:
										dialog.dismiss();
										break;
									}
								}
							});
						}
						break;
					case 2:
						DatabaseHelper db = new DatabaseHelper(mContext);
						DownloadLaterItem dlItem = new DownloadLaterItem(item.getAvatar(), item.getTitle(), item.getAuthor(), item.getApplicationId());
						dlItem.setPrice1(item.getPrice());
						dlItem.setPrice2(item.getPrice2());
						dlItem.setPackageName(item.getPackageName());
						dlItem.setType("apps");
						boolean added = db.addDownloadLater(dlItem);
						if(added){
							Toast.makeText(mContext, String.format(getResources().getString(R.string.saved), item.getTitle()), Toast.LENGTH_SHORT).show();
						} else {
							Toast.makeText(mContext, String.format(getResources().getString(R.string.item_exist), item.getTitle()), Toast.LENGTH_SHORT).show();
						}
						break;
					}
				}
			});
			popupMenuCompat.show(v);
		}
	}
	
	private void validAndBuy(int price, String tymType, ContentItemInfo item, int versionId){
		if(item.getBought() == 1){
			if(pDialog == null){
				pDialog = ProgressDialogManager.showProgressDialog(getActivity(), R.string.loading);
			}
			bgTask.buyContent("",Utils.getStaticAccessToken(getActivity()), item.getApplicationId(), versionId);
		} else {
			if(tymType.equals("green")){
				if(greenTym < price && greenTym != -1){
					AlertDialogManager am = new AlertDialogManager(mContext);
					am.showButtonsDialog(R.string.lack_of_tym, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							switch (which) {
							case DialogInterface.BUTTON_POSITIVE:
//								Intent intent = new Intent(getActivity(), PaymentActivity.class);
//								Bundle bundle = new Bundle();
//								bundle.putInt(AccountActivity.KEY_GREEN_TYM, greenTym);
//								bundle.putInt(AccountActivity.KEY_PURPLE_TYM, purpleTym);
//								intent.putExtras(bundle);
//								startActivity(intent);
								List<String> scopes = new ArrayList<String>();
								scopes.add("user.info");
								scopes.add("user.email");
								TopupAPI.getInstance().setContext(getActivity()).topupTYM(scopes, "");
								break;
							case DialogInterface.BUTTON_NEGATIVE:
								dialog.dismiss();
								break;
							}
						}
					});
				} else if(greenTym == -1){
					AlertDialogManager am = new AlertDialogManager(mContext);
					am.showPositiveDialog(R.string.cannot_buy_thistime, android.R.string.ok, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
				} else {
					Intent intent = new Intent(getActivity(), ConfirmBuyActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString(Constants.KEY_IMAGE, item.getAvatar());
					bundle.putString(Constants.KEY_NAME, item.getTitle());
					bundle.putString(Constants.KEY_AUTHOR, item.getAuthor());
					bundle.putInt(Constants.KEY_PRICE_1, item.getPrice());
					bundle.putInt(Constants.KEY_PRICE_2, item.getPrice2());
					bundle.putLong(Constants.KEY_VERSION, Long.valueOf(versionId));
					bundle.putString(Constants.KEY_EP, versionName);
					bundle.putString(Constants.KEY_SLUG, item.getApplicationId());
					intent.putExtras(bundle);
					startActivityForResult(intent, 0);
				}
			} else if(tymType.equals("purple")){
				if(purpleTym < price && purpleTym != -1){
					AlertDialogManager am = new AlertDialogManager(mContext);
					am.showButtonsDialog(R.string.lack_of_tym, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							switch (which) {
							case DialogInterface.BUTTON_POSITIVE:
//								Intent intent = new Intent(getActivity(), PaymentActivity.class);
//								Bundle bundle = new Bundle();
//								bundle.putInt(AccountActivity.KEY_GREEN_TYM, greenTym);
//								bundle.putInt(AccountActivity.KEY_PURPLE_TYM, purpleTym);
//								intent.putExtras(bundle);
//								startActivity(intent);
								List<String> scopes = new ArrayList<String>();
								scopes.add("user.info");
								scopes.add("user.email");
								TopupAPI.getInstance().setContext(getActivity()).topupTYM(scopes, "");
								break;
							case DialogInterface.BUTTON_NEGATIVE:
								dialog.dismiss();
								break;
							}
						}
					});
				} else if(purpleTym == -1){
					AlertDialogManager am = new AlertDialogManager(mContext);
					am.showPositiveDialog(R.string.cannot_buy_thistime, android.R.string.ok, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
				} else {
					Intent intent = new Intent(getActivity(), ConfirmBuyActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString(Constants.KEY_IMAGE, item.getAvatar());
					bundle.putString(Constants.KEY_NAME, item.getTitle());
					bundle.putString(Constants.KEY_AUTHOR, item.getAuthor());
					bundle.putInt(Constants.KEY_PRICE_1, item.getPrice());
					bundle.putInt(Constants.KEY_PRICE_2, item.getPrice2());
					bundle.putLong(Constants.KEY_VERSION, Long.valueOf(versionId));
					bundle.putString(Constants.KEY_SLUG, item.getApplicationId());
					intent.putExtras(bundle);
					startActivityForResult(intent, 0);
				}
			} else if(tymType.equals("free")){
				bgTask.buyContent("home", Utils.getStaticAccessToken(getActivity()), item.getApplicationId(), versionId);
			}
		}
	}
	
	public void onEventMainThread(BuySuccessEvent event){
		if(event.getTopType().equalsIgnoreCase("home")){
			String accessToken = Utils.getStaticAccessToken(getActivity());
			bgTask.getDownloadLink("home", accessToken, event.getSlug(), event.getVersionId(), Utils.getStaticIsRooted(getActivity()), "direct");
		}
	}
	
	public void onEventMainThread(BuyFailEvent event){
		if(event.getTopType().equalsIgnoreCase("home")){
			if(pDialog != null){
				pDialog.dismiss();
			}
			AppMsg.makeText(getActivity(), event.getMessage(), AppMsg.STYLE_ALERT, null).show();
		}
	}
	
	public void onEventMainThread(GetDownloadLinkSuccess event){
		if(event.getTopType().equalsIgnoreCase("home")){
			if(pDialog != null){
				pDialog.dismiss();
			}
			if(contentItem.getInstallAttachApplication() == 1){
				accessToken = Utils.getStaticAccessToken(getActivity());
				bgTask.buyAttachedContent(accessToken, contentItem.getAttachApplicationSlug(), 0);
			}
				DownloadLink download = event.getDl();
				List<String> extraUrls = download.getExtraDownloads();
				if(extraUrls.size() > 0){
					for(String extraUrl : extraUrls){
						Uri srcUri = Uri.parse(extraUrl.replace(" ", "%20"));
						DownloadManager.Request request = new Request(srcUri);
						if(extraUrl.endsWith("obb")){
							String obbDir = StorageUtils.OBB_ROOT + contentItem.getPackageName() + "/";
							File obb = new File(obbDir);
							if(!obb.exists()){
								obb.mkdirs();
							}
							request.setDestinationUri(Uri.fromFile(new File(obbDir + Utils.getFileName(extraUrl))));	
						} else {
							request.setDestinationUri(Uri.fromFile(new File(StorageUtils.APPS_ROOT + Utils.getFileName(extraUrl))));
						}
						request.setTitle(String.format(getResources().getString(R.string.additional_file), contentItem.getTitle()));
						request.setDescription(contentItem.getAvatar());
						request.setMimeType(StorageUtils.APPS_ROOT.toLowerCase(Locale.US));
						downloadManager.enqueue(request);
					}
				}
				String url = download.getDownload();
				Uri srcUri = Uri.parse(url.replace(" ", "%20"));
				DownloadManager.Request request = new Request(srcUri);
				request.setTitle(contentItem.getTitle());
				request.setDescription(contentItem.getAvatar());
				setDownloadData(request, url);
				downloadManager.enqueue(request);
		}
	}
	
	public void onEventMainThread(GetDownloadLinkFailEvent e){
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		AppMsg.makeText(getActivity(), e.getMessage(), AppMsg.STYLE_ALERT, null).show();
	}
	
	private void setDownloadData(Request request, String url){
		request.setWhere("home");
		request.setMimeType(StorageUtils.APPS_ROOT.toLowerCase(Locale.US));
		request.setDestinationUri(Uri.fromFile(new File(StorageUtils.APPS_ROOT + Utils.getFileName(url))));
	}
	
	public void onEventMainThread(final Event.DownloadFailEvent e){
		if(e.getReferer() == null){
			return;
		}
		if(e.getReferer().equalsIgnoreCase("home")){
			if(e.getMessage() != null){
				if(e.getMessage().contains("exist")){
					AlertDialogManager am = new AlertDialogManager(getActivity());
					am.showFileDowloadDialog("apps", R.string.install_already_exist_file, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							switch (which) {
							case DialogInterface.BUTTON_POSITIVE:
								boolean autoInstall = getActivity().getSharedPreferences(Constants.SHARED_NAME, Activity.MODE_PRIVATE).getBoolean(SettingsActivity.KEY_AUTO_INSTALL, false);
					    		if(!autoInstall){
					    			Utils.installAPK(getActivity(), StorageUtils.APPS_ROOT + Utils.getFileName(e.getPath()));
					    		} else {
					    			InstallBackgroundTask task = new InstallBackgroundTask(getActivity());
					    			task.execute(StorageUtils.APPS_ROOT + Utils.getFileName(e.getPath()), contentItem.getTitle());
					    		}
								break;
							case DialogInterface.BUTTON_NEGATIVE:
								Utils.deleteFile(StorageUtils.APPS_ROOT + Utils.getFileName(e.getPath()));
								break;
							case DialogInterface.BUTTON_NEUTRAL:
								dialog.dismiss();
								break;
							}
						}
					});
				} else {
					AppMsg.makeText(getActivity(), e.getMessage(), AppMsg.STYLE_ALERT, null).show();
				}
			}
			downloadManager.remove(e.getId());
		}
	}
}
